//
//  UserAccoutviewModel.swift
//  sinaweibo
//
//  Created by icefs2 on 15/11/12.
//  Copyright © 2015年 icefs2. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccoutviewModel: NSObject {
    //增加UserAccout属性
    var accout: UserAccout?
    //在init中获取用户账户
    override init() {
        accout = UserAccout.loadAccout()
    }
    // 用户是否登陆属性
    var userlogin: Bool {
    return accout?.access_token != nil
    }
    
    var token: String? {
        return accout?.access_token
    }
    var userName: String? {
        return accout?.name
    }
    var headURL: NSURL? {
        return NSURL(string: (accout?.avatar_large ?? ""))
    }
    
    //获取token
    func loadToken(code: String, finished: (error: NSError?) -> ()) {
        let urlstr = "https://api.weibo.com/oauth2/access_token"
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let parameters = ["client_id" : appkey, "client_secret" : appsecret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" :redirect_uri]
        AFN.POST(urlstr, parameters: parameters, success: { (_, result) -> Void in
            print(result)
            if let dict = result as? [String : AnyObject] {
                let account = UserAccout(dict: dict)
             
              self.loadUserInfor(account, finished: finished)
                print(account)
            }
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    //开始加载用户数据
    private func loadUserInfor(account: UserAccout, finished: (error: NSError?) -> ()) {
        let urlstring = "https://api.weibo.com/2/users/show.json"
        let AFN = AFHTTPSessionManager()
        let parameters = ["access_token" : account.access_token!, "uid" : account.uid!]
        AFN.GET(urlstring, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String : AnyObject] {
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                account.saveAccount()
                print(account)
                //执行闭包
                finished(error: nil)
                
            }
            
            
            }) { (_, error) -> Void in
                finished(error: error)
                print(error)
        }
    }
}
